//
//  GCMTaskListViewController.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/3/22.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "GCMTaskListViewController.h"
#import "GCMTaskListModel.h"
#import "GCMTaskListTableViewCell.h"
#import "GCMTaskDetailViewController.h"

@interface GCMTaskListViewController ()<UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate>{
    
    NSMutableArray *_DataArray;
    NSMutableArray *_reciveFenleiArray;
    NSMutableArray *_reciveXiaoquArray;
    UIButton * _leftbutton;
    UIButton * _rightbutton;
    UITableView *_tableView;
    NSString *_returnMsg;
    NSMutableArray *_yearArr;
    NSMutableArray *_monthArr;
    UITableView *_tableV;
    NSMutableArray *_dataSource;
    NSInteger _currentPage;
    
    
}


@end

@implementation GCMTaskListViewController


-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO;
    [self initData];
    [self downLoadData];
}

- (void)viewDidLoad {
    _currentPage = 1;
    
    [self createTableView];
    //    下拉刷新
    _tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        // 进入刷新状态后会自动调用这个block
        [self downloadTableViewData];
        [_tableV.mj_header endRefreshing];
        
    }];
    //    上拉加载
    _tableV.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 进入加载状态后会自动调用这个block
        _currentPage ++;
        NSString *pageStr  = [NSString stringWithFormat:@"%ld",_currentPage];
        
        [self downloadNextPageTableViewDataWith:pageStr];
        [_tableV.mj_footer endRefreshing];
    }];

}

-(void)createTableView{
    
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0,50, SCREEN_WIDTH, SCREEN_HEIGHT  - 50)];
    _tableV.backgroundColor  = [UIColor redColor];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    _tableV.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    [self.view addSubview:_tableV];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GCMTaskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[GCMTaskListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    [cell setBackgroundColor:[UIColor colorWithRed:.93 green:.93 blue:.93 alpha:1]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //    cell.textLabel.textColor = [UIColor colorWithRed:0.39 green:0.39 blue:0.39 alpha:1];
    GCMTaskListModel *listModel = _dataSource[indexPath.row];
    //NSLog(@"%@",listModel.contact);
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    [cell setListModel:listModel];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 110;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GCMTaskDetailViewController * taskVC = [[GCMTaskDetailViewController alloc]init];
    GCMTaskListModel *model = _dataSource[indexPath.row];
    taskVC.idd = model.idd;
    [self.navigationController pushViewController:taskVC animated:YES ];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"任务详情";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = backItem;
}


//初始化数据

-(void)initData{
    
    _reciveFenleiArray = [[NSMutableArray alloc]init];
    _dataSource = [[NSMutableArray alloc]init];
}

-(void)downLoadData{
    
    [GCMHostSearchHttpRequst postDataWithUserName:[GCMUserInfo instance].realName Success:^(id obj, NSError *err) {
        _reciveXiaoquArray  = [NSMutableArray arrayWithArray:obj];
         //NSLog(@"小区%@",_reciveXiaoquArray);
        //    请求接待的分类数据
        [GCMReviceHttpRequst postFenLeiDataWithURL:TASKSTATE_URL Success:^(id obj, NSError *err) {
            //NSLog(@"%@",obj);
            _reciveFenleiArray = obj;
            //NSLog(@"...%@",_reciveFenleiArray);
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"taskXiaoQu"];
            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"taskLeiXing"];
            [self createUI];
            [self downloadTableViewData];
        }];
    }];
}

-(void)downloadTableViewData{
    NSString *xqstr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskXiaoQu"];
    NSString *leixingStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskLeiXing"];
    [GCMTaskHttpRequst postTaskListDataWithcourtId:xqstr Withremark:leixingStr WithPage:@"1" WithUserName:[GCMUserInfo instance].realName Success:^(id obj, NSError *err) {
        //NSLog(@"++--=+%@",obj);
        [_dataSource removeAllObjects];
        _dataSource = obj;
        [_tableV reloadData];
    }];

    
}
-(void)downloadNextPageTableViewDataWith:(NSString*)pagestr{

    //    改变当前页
    //_currentPage ++;

    NSString *xqstr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskXiaoQu"];
    NSString *leixingStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskLeiXing"];
    //NSLog(@"-----arry---%@",_reciveFenleiArray[indexPath.row]);
    [GCMTaskHttpRequst postTaskListDataWithcourtId:xqstr Withremark:leixingStr WithPage:pagestr WithUserName:[GCMUserInfo instance].realName Success:^(id obj, NSError *err) {
        //NSLog(@"++--=+%@",obj);
        [_dataSource addObjectsFromArray:obj];
        [_tableV reloadData];
    }];

    
}

- (void)createUI{
    WKProgressHUD *hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0.98,0.98,0.98,1});
    
    _leftbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH/2, 50)];
    _rightbutton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2    , 64, SCREEN_WIDTH/2 , 50)];
    _leftbutton.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    _rightbutton.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);//设置title在button上的位置（上top，左left，下bottom，右right）
    [_leftbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_leftbutton setTitle:@"小区" forState:UIControlStateNormal];
    [_rightbutton setTitle:@"我的全部接待" forState:UIControlStateNormal];
    [_leftbutton setBackgroundColor:[UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1]];
    [_rightbutton setBackgroundColor:[UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1]];
    [_rightbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    UIImageView *rimageViwe = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 40, 10, 30, 30)];
    [rimageViwe setImage:[UIImage imageNamed:@"xiala"]];
    [_rightbutton addSubview:rimageViwe];
    UIImageView *limageViwe = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 40, 10, 30, 30)];
    [limageViwe setImage:[UIImage imageNamed:@"xiala"]];
    [_leftbutton addSubview:limageViwe];
    [_leftbutton.layer setBorderWidth:1.f];
    [_leftbutton.layer setBorderColor:color];
    [_leftbutton.layer setCornerRadius:0];
    [_rightbutton.layer setBorderColor:color];
    [_rightbutton.layer setBorderWidth:1.f];
    [_rightbutton.layer setCornerRadius:0];
    [_leftbutton addTarget:self action:@selector(onLeftbutton) forControlEvents:UIControlEventTouchUpInside];
    [_rightbutton addTarget:self action:@selector(onRightbutton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftbutton];
    [self.view addSubview:_rightbutton];    //_yearArr = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"%d",[dastr intValue]-1],dastr, nil];
    NSMutableArray *fenleiA = [[NSMutableArray alloc]init];
    NSMutableArray *fenleiB = [[NSMutableArray alloc]init];
    for (NSDictionary *dic in _reciveFenleiArray) {
        NSString *str =[ NSString stringWithFormat:@"%@", [dic valueForKey:@"value"] ];
        [fenleiA addObject:str];
        _monthArr = [NSMutableArray arrayWithArray:fenleiA];
       // NSLog(@",,,,,%@",_monthArr);
    }
    for (NSDictionary *dic1 in _reciveXiaoquArray) {
        NSString *str =[ NSString stringWithFormat:@"%@", [dic1 valueForKey:@"name"] ];
        [fenleiB addObject:str];
        _yearArr = [NSMutableArray arrayWithArray:fenleiB];
        //NSLog(@"ququ2 区%@",_yearArr);
    }
    _leftbutton.titleLabel.font = [UIFont systemFontOfSize: 15];
    _rightbutton.titleLabel.font = [UIFont systemFontOfSize: 15];
    [_leftbutton setTitle:_yearArr[0] forState:UIControlStateNormal];
    [_rightbutton setTitle:_monthArr[0] forState:UIControlStateNormal];
    [hud dismiss:YES];
}


#pragma mark--展示下拉菜单
-(void)onLeftbutton{
    
    __weak typeof(self)weakSelf=self;
    if (!_leftmuen) {
        
        _leftmuen=[[SCXCreateAlertView alloc]initWithNameArray:_yearArr andMenuOrigin:CGPointMake(0,114 ) andMenuWidth:SCREEN_WIDTH/2 andHeight:40 andLayer:0 andTableViewBackGroundColor:[UIColor clearColor] andIsSharp:YES andType:kNavigationPop];
        _leftmuen.delegate = weakSelf;
        _leftmuen.tableViewDelegate=self;
        _leftmuen.dismiss=^(){
            [weakSelf.leftmuen removeFromSuperview];
            _leftmuen=nil;
        };
        [self.view addSubview:_leftmuen];
    }
    else{
        [_leftmuen dismissWithCompletion:^(SCXCreateAlertView *create){
            [_leftmuen removeFromSuperview];
            _leftmuen = nil;
        }];
    }
}

#pragma mark--自定义下拉菜单代理方法,点击下拉菜单某一行时候对应的响应时间，点击完成后试图要消失，用一个block通知；
-(void)tableViewDidSelectRowAtIndexPath:(NSIndexPath *)indexPath andPopType:(popType)popViewType{
    
    //改变导航栏文字
    if (popViewType == kNavigationPop) {
        [_leftbutton setTitle:_yearArr[indexPath.row] forState:UIControlStateNormal];
    }
    
    [[NSUserDefaults standardUserDefaults]setObject:[_reciveXiaoquArray[indexPath.row] valueForKey:@"id"] forKey:@"taskXiaoQu"];
    //NSLog(@"接待类型%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"reciveLeiXing"]);
    NSString *xqstr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskXiaoQu"];
    NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskLeiXing"];
    //NSLog(@"-----arry---%@",_reciveFenleiArray[indexPath.row]);
    [GCMTaskHttpRequst postTaskListDataWithcourtId:xqstr Withremark:str WithPage:@"1" WithUserName:[GCMUserInfo instance].realName Success:^(id obj, NSError *err) {
        //NSLog(@"++--=+%@",obj);
        _dataSource = obj;
        [_tableV reloadData];
    }];
    
    [_leftmuen dismissWithCompletion:nil];//点击完成后视图消失;
    
}
#pragma mark---同上
-(void)onRightbutton{
    __weak typeof(self)weakSelf=self;
    if (!_rightmuen) {
        
        _rightmuen=[[SCXCreateAlertView2 alloc]initWithNameArray:_monthArr andMenuOrigin:CGPointMake(SCREEN_WIDTH/2,114 ) andMenuWidth:SCREEN_WIDTH/2 andHeight:40 andLayer:0 andTableViewBackGroundColor:[UIColor clearColor] andIsSharp:YES andType:kNavigationPop2];
        _rightmuen.delegate = weakSelf;
        _rightmuen.tableViewDelegate=self;
        _rightmuen.dismiss=^(){
            [weakSelf.rightmuen removeFromSuperview];
            _rightmuen=nil;
        };
        [self.view addSubview:_rightmuen];
    }
    else{
        [_rightmuen dismissWithCompletion:^(SCXCreateAlertView2 *create) {
            [_rightmuen removeFromSuperview];
            _rightmuen = nil;
        }];
    }
}

-(void)secondtableViewDidSelectRowAtIndexPath:(NSIndexPath *)indexPath andPopType:(popType2)popViewType{
    //改变导航栏文字
    if (popViewType==kNavigationPop2) {
        [_rightbutton setTitle:_monthArr[indexPath.row] forState:UIControlStateNormal];
    }
    
    [[NSUserDefaults standardUserDefaults]setObject:[_reciveFenleiArray[indexPath.row] valueForKey:@"remark"] forKey:@"taskLeiXing"];
    //NSLog(@"接待类型%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"reciveLeiXing"]);
    NSString *xqstr = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskXiaoQu"];
    NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:@"taskLeiXing"];
    //NSLog(@"-----arry---%@",_reciveFenleiArray[indexPath.row]);
    [GCMTaskHttpRequst postTaskListDataWithcourtId:xqstr Withremark:str WithPage:@"1" WithUserName:[GCMUserInfo instance].realName Success:^(id obj, NSError *err) {
        NSLog(@"++--=+%@",obj);
        _dataSource = obj;
        [_tableV reloadData];
    }];

    [_rightmuen dismissWithCompletion:nil];//点击完成后视图消失;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
